package com.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chat.domain.dto.chat.ChatQueryDTO;
import com.chat.domain.pojo.Group;
import com.chat.domain.pojo.Message;
import com.chat.domain.pojo.User;
import com.chat.domain.vo.ChatVO;
import com.chat.service.ChatService;
import com.chat.service.GroupService;
import com.chat.service.MessageService;
import com.chat.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author wb
 * @since 2025-06-07
 */

@Service
public class ChatServiceImpl implements ChatService {

    @Autowired
    private UserService userService;
    @Autowired
    private GroupService groupService;
    @Autowired
    private MessageService messageService;


    @Override
    public List<ChatVO> getChats(ChatQueryDTO chatQueryDTO) {
        List<ChatVO> chats = new ArrayList<>();

        Integer userId = chatQueryDTO.getUserId();
        Integer chatType = chatQueryDTO.getChatType();
        String chatName = chatQueryDTO.getChatName();

        if (chatType != null && !Objects.equals(chatType, 2)) {
            List<User> friends = userService.getFriendsByUserId(userId);
            friends.forEach(item -> {
                ChatVO vo = new ChatVO();
                vo.setChatId("user-" + item.getId());
                vo.setType(1);
                vo.setName(item.getRealName());
                vo.setAvatar(item.getAvatar());
                vo.setRemark(item.getRemark());
                vo.setDescription(item.getDescription());

                chats.add(vo);
            });
        }


        if (chatType != null && !Objects.equals(chatType, 1)) {
            List<Group> groups = groupService.getGroupsByUserId(userId);
            groups.forEach(item -> {
                ChatVO vo = new ChatVO();
                vo.setChatId("group-" + item.getId());
                vo.setType(2);
                vo.setName(item.getName());
                vo.setAvatar(item.getAvatar());
                vo.setRemark(item.getRemark());
                vo.setDescription(item.getDescription());

                chats.add(vo);
            });
        }

        if (chatName != null && !chatName.isEmpty()) {
            return chats.stream().filter(item -> item.getName().contains(chatName)).toList();
        }


        return chats;
    }

    @Override
    public Boolean clean(String chatId) {
        if (chatId != null && !chatId.isEmpty()) {
            messageService.remove(new LambdaQueryWrapper<Message>().eq(Message::getChatId, chatId));
        }

        return true;
    }
}
